<?php

namespace App\Service;


use App\Model\OrderSubscribe;
use App\Model\SubOption;
use App\Model\User;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;

class AppleService extends BaseService
{

    /**
     * @Inject()
     * @var HttpService
     */
    public $httpService;


    /**
     *返回订阅票据的真实性
     * @param $orderNo
     * @param $receiptData
     * @return bool
     */
    public function checkSubscribeBill($orderNo, $receiptData)
    {

        $orderInfo = OrderSubscribe::where(['order_no' => $orderNo, 'status' => 0])->first();
        if (is_null($orderInfo)) {
            return false;
        }

        $result = $this->verifyReceipt($receiptData);


        if ($result == false) {
            return false;
        }


        if ($orderInfo['code'] == $result['product_id']) {// 订阅产品对上则算成功

            $updateData = [
                'original_transaction_id' => $result['original_transaction_id'],
                'original_purchase_date_ms' => $result['original_purchase_date_ms'],
                'expires_date_ms' => $result['expires_date_ms'],
                'pay_id' => $result['pay_id'],
                'web_order_line_item_id' => $result['web_order_line_item_id'],
                'start_date' => $result['original_purchase_date_ms'],
                'renew' => $result['expires_date_ms'],
                'receipt_data' => $receiptData,
                'update_time' => time(),
            ];

            $rel = OrderSubscribe::where(['order_no' => $orderNo])->update($updateData);

            if ($rel) {
                return true;
            }
        }
        return false;

    }


    /**
     * 得到票据查询的数据 成功且有效返回指定数据
     * @param $receiptData
     * @return array|false
     */
    public function verifyReceipt($receiptData)
    {

        $env = env('APP_ENV', 'dev');
        if ($env == 'dev') {
            $url = env('IAP_URL_DEV', 'https://sandbox.itunes.apple.com/verifyReceipt');
        } else {
            $url = env('IAP_URL_PRO', 'https://sandbox.itunes.apple.com/verifyReceipt');
        }
        $password = env('IAP_PASSWORD', '1d6e0194a7284e5883fe4b27f724d0cc');

        $data = [
            'receipt-data' => $receiptData,
            'password' => $password,
            'exclude-old-transactions' => true
        ];

        $options['headers'] = [
            'Content-Type' => 'application/json',
        ];
        $options['json'] = $data;

        $result = $this->httpService->request($url, $options, 'POST');


        if ($result) {

            if (isset($result['status']) && $result['status'] == 0) {

                //返回结果有效处理
                if (!empty($result['latest_receipt_info'][0])) {
                    $latestReceipt = $result['latest_receipt_info'][0];

                    var_dump($latestReceipt['expires_date_ms']);

                    // 测试都算没过期
                    if (isset($latestReceipt['expires_date_ms']) && $latestReceipt['expires_date_ms'] + 999999999999 >= time() * 1000) {
                        //订阅有效 目前判断在有效期内就算有效


                        return [
                            'original_transaction_id' => $latestReceipt['original_transaction_id'],
                            'original_purchase_date_ms' => $latestReceipt['original_purchase_date_ms'] / 1000,
                            'expires_date_ms' => $latestReceipt['expires_date_ms'] / 1000,
                            'web_order_line_item_id' => $latestReceipt['web_order_line_item_id'],
                            'pay_id' => $latestReceipt['transaction_id'],
                            'product_id' => $latestReceipt['product_id']
                        ];

                    } else {
                        logger()->info('查询到订阅已经不再有效期了', [$result]);


                         //临时返回
//                        return [
//                            'original_transaction_id' => $latestReceipt['original_transaction_id'],
//                            'original_purchase_date_ms' => $latestReceipt['original_purchase_date_ms'] / 1000,
//                            'expires_date_ms' => $latestReceipt['expires_date_ms'] / 1000,
//                            'web_order_line_item_id' => $latestReceipt['web_order_line_item_id'],
//                            'pay_id' => $latestReceipt['transaction_id'],
//                            'product_id' => $latestReceipt['product_id']
//                        ];


                        //订阅无效
                    }
                }
            } else {
                //处理请求报错的异常
                /* 21000
                //到AppStore的请求不是用的HTTP POST方法
                //
                //21001
                //AppStore已不再发送此状态码
                //
                //21002
                //在receipt-data属性中的数据格式有误，或者服务遇到临时问题。再试一次。
                //
                //21003
                //该收据无法认证
                //
                //21004
                //你提供的共享密钥与账户文件的共享密钥不匹配
                //
                //21005
                //收据服务器暂时无法提供收据。再试一次
                //
                //21006
                //该收据有效，但订阅已过期。当该状态码返回到你的服务器时，收据数据也会被解码作为响应的一部分。仅针对自动续期订阅的iOS 6样式的交易收据。
                //
                //21007
                //该收据来自于测试环境。但它被发送到了生产环境来验证。
                //
                //21008
                //该收据来自于生产环境，但它被发送到测试环境验证。
                //
                //21009
                //内部数据访问错误。重试一次
                //
                //21010
                //用户账户找不到或已经被删除
                */

                logger()->info('查询到订阅出错', [$result]);
            }

        } else {
            logger()->info('请求苹果第三方票据查询失败', [$result]);
            // 没查询到得流程 处理
        }

        return false;

    }


    public function subscribeRestore($uid, $receiptData)
    {

        $result = $this->verifyReceipt($receiptData);
        logger()->info('resrore', [$result]);

        if ($result && isset($result['product_id'])) {

            $subInfo = SubOption::where(['code' => $result['product_id']])->first();
            $renew = SubOption::countRenewDay($subInfo['unit'], $subInfo['quantity']);

            $userUpdateData = [
                'role' => 1,
                'update_time' => time(),
                'become_due' => $result['expires_date_ms'] ?? strtotime($renew)
            ];
            try {
                $rel = User::where(['id' => $uid])->update($userUpdateData);
                return true;
            } catch (\Exception $e) {

            }
        }


        return false;

    }


    public function subscriptionCallback($params)
    {


        $password = env('IAP_PASSWORD', '1d6e0194a7284e5883fe4b27f724d0cc');
        if ($params && $params['password'] == $password) {//收到数据并且密码相同进入回调处理

            switch ($params['notification_type']) {
                case 'DID_RENEW'://表示客户的订阅已经成功自动续订了一个新的交易周期。  可以进行续订操作√√√√
                    $this->renew($params);
                    break;
                case 'INTERACTIVE_RENEWAL'://表示客户以交互的方式续订了一个订阅。可能通过你的App的界面或者在AppStore的账户订阅设置里。立即提供服务。 可以进行续订操作√√√√
                    $rel = $this->renew($params);
                    break;
                case 'DID_CHANGE_RENEWAL_STATUS'://表示订阅续期状态的一个更改。在JSON响应中，检查auto_renew_status_change_date_ms字段来了解最新状态更新的日期和时间。检查auto_renew_status字段来了解当前续订的状态。
                    $rel = $this->renew($params);
                    break;
                case 'DID_RECOVER'://重新续费上了
                    $rel = $this->renew($params);
                    break;
            }
        }

    }


    /**
     * 进行续费
     * @param $params
     * @return bool|void
     */
    public function renew($params)
    {
        if ($params['unified_receipt']['latest_receipt_info'][0]) {
            $latestReceipt = $params['unified_receipt']['latest_receipt_info'][0];
        } else {
            logger()->info('数据类型错误，没有最近的一单不进行处理');
            return false;
        }
        $tempData = [
            'original_transaction_id' => $latestReceipt['original_transaction_id'],
            'original_purchase_date_ms' => $latestReceipt['original_purchase_date_ms'] / 1000,
            'expires_date_ms' => $latestReceipt['expires_date_ms'] / 1000,
            'web_order_line_item_id' => $latestReceipt['web_order_line_item_id'],
            'pay_id' => $latestReceipt['transaction_id'],
            'product_id' => $latestReceipt['product_id'],
        ];
        $lastOrder = OrderSubscribe::where(['original_transaction_id' => $tempData['original_transaction_id']])->orderBy('id', 'desc')->first();

        //在有效期内则续费
        if (isset($latestReceipt['expires_date_ms']) && $latestReceipt['expires_date_ms'] >= time() * 1000) {
            if ($lastOrder) {//找到上一期的 订单
                $exists = OrderSubscribe::where(['pay_id' => $tempData['pay_id']])->exists();

                //如果订单号已经使用过了则不进行下面操作
                if ($exists) {
                    logger()->info('苹果回调订单已处理，进行了再次回调，不进行其他操作');
                    return false;
                }

                $userInfo = User::where(['id' => $lastOrder['uid']])->first();

                if ($userInfo) {//找到目前现在的用户

                    Db::beginTransaction();
                    try {
                        $orderNo = OrderSubscribe::createOrderNo();

                        $newOrder = [
                            'order_no' => $orderNo,
                            'uid' => $lastOrder['uid'],
                            'account' => $userInfo['account'],
                            'level' => $lastOrder['level'],
                            'type' => 2,//续费
                            'price' => $lastOrder['price'],
                            'code' => $lastOrder['code'],
                            'create_time' => time(),
                            'status' => 1,
                            'original_transaction_id' => $tempData['original_transaction_id'],
                            'original_purchase_date_ms' => $tempData['original_purchase_date_ms'],
                            'expires_date_ms' => $tempData['expires_date_ms'],
                            'pay_id' => $tempData['pay_id'],
                            'web_order_line_item_id' => $tempData['web_order_line_item_id'],
                            'start_date' => $tempData['original_purchase_date_ms'],
                            'renew' => $tempData['expires_date_ms'],
                            'receipt_data' => $params['unified_receipt']['latest_receipt'],
                            'update_time' => time(),
                        ];

                        //记录续费订单
                        OrderSubscribe::insert($newOrder);

                        //改变用户信息
                        $userUpdateData = [
                            'member' => 1,
                            'update_time' => time(),
                            'member_type' => $lastOrder['level'],
                            'become_due' => $tempData['expires_date_ms'],
                            'auto_renew_status' => $params['auto_renew_status'] == 'true' ? 1 : 0,
                        ];

                        User::where(['id' => $lastOrder['uid']])->update($userUpdateData);

                        Db::commit();
                        return true;
                    } catch (\Exception $e) {
                        recordExceptionLog('苹果回调', json_encode($e->getMessage()));
                        Db::rollBack();
                        return false;
                    }

                } else {
                    logger()->info('没有找到初始订单的用户,不进行处理，订单号为：' . $tempData['original_transaction_id']);
                }
            } else {
                logger()->info('没有找到系统有初始订单,不进行处理，订单号为：' . $tempData['original_transaction_id']);
            }
        } else {
            logger()->info('订阅周期不在有效期内了');
        }


    }


}
